package system

import (
	"context"
	"slices"

	"portal/internal/errorx"
	"portal/internal/svc"
	"portal/internal/tool/auth"
	"portal/internal/types"
	"portal/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListRoleLogic struct {
	logx.Logger
	ctx       context.Context
	svcCtx    *svc.ServiceContext
	menuModel model.SysMenuModel
	roleModel model.SysRoleModel
}

func NewListRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListRoleLogic {
	return &ListRoleLogic{
		Logger:    logx.WithContext(ctx),
		ctx:       ctx,
		svcCtx:    svcCtx,
		menuModel: model.NewSysMenuModel(svcCtx.Orm),
		roleModel: model.NewSysRoleModel(svcCtx.Orm),
	}
}

func (l *ListRoleLogic) ListRole(req *types.ListRoleRequest) (resp *types.CommonResponse, err error) {
	// todo: add your logic here and delete this line
	err = auth.HasPermission(l.menuModel, l.ctx, "system:role:query")
	if err != nil {
		return nil, errorx.Unauthorized
	}
	authinfo, err := auth.GetAuth(l.ctx)
	if err != nil {
		return nil, errorx.AuthNoFound
	}
	// 查询当前用户所属的所有角色列表
	roledtos, err := l.roleModel.GetListByCondition(l.ctx, nil, authinfo.UserId, req)
	if err != nil {
		return nil, errorx.SqlSearchError
	}
	rolevos := make([]*types.Role, 0)
	for _, fval := range roledtos {
		rolevos = append(rolevos, &types.Role{
			RoleId:     fval.RoleId,
			RoleName:   fval.RoleName,
			RoleKey:    fval.RoleKey,
			RoleSort:   fval.RoleSort,
			Status:     fval.Status,
			UpdateTime: fval.UpdateTime,
			CreateTime: fval.CreateTime,
		})
	}
	slices.SortFunc(rolevos, func(a *types.Role, b *types.Role) int {
		return int(a.RoleSort - b.RoleSort)
	})

	return &types.CommonResponse{
		Status: 200,
		Msg:    "查询成功",
		Data: rolevos,
	}, nil
}
